const express = require('express');
const router = express.Router();
const db = require('../config/db');

// 测试数据库连接
router.get('/', async (req, res) => {
  try {
    const [result] = await db.query('SELECT 1');
    res.json({ message: '数据库连接成功', result });
  } catch (error) {
    res.status(500).json({ error: error.message });
  }
});
// 用户登录接口
router.post('/users/login', async (req, res) => {
  try {
    const { phone, password } = req.body;
    console.log('登录请求:', { phone, password });

    // 查询用户，修改返回字段
    const [users] = await db.query(
      'SELECT id, phone, password, nickname, avatar FROM users WHERE phone = ? AND password = ?',
      [phone, password]
    );
    console.log('查询结果:', users);
    
    if (users.length === 0) {
      return res.status(401).json({ error: '手机号或密码错误' });
    }

    const user = users[0];
    const token = Date.now().toString();

    res.json({
      token,
      userInfo: {
        id: user.id,
        nickname: user.nickname,
        phone: user.phone,
        avatarUrl: user.avatar  // 修改这里，使用数据库中的字段名
      }
    });
  } catch (error) {
    console.error('登录错误:', error);
    res.status(500).json({ error: error.message });
  }
});

// 获取商品详情
router.get('/goods/:id', async (req, res) => {
  try {
    const goodsId = req.params.id;
    const [dishes] = await db.query('SELECT * FROM dishes WHERE id = ?', [goodsId]);
    console.log('查询结果:', dishes);
    
    if (dishes.length === 0) {
      return res.status(404).json({ error: '商品不存在' });
    }

    const dish = dishes[0];
    
    res.json({
      code: 0,
      data: {
        id: dish.id,
        name: dish.name,
        price: dish.price,
        image: dish.image,
        description: dish.description,
        category_id: dish.category_id,
        status: dish.status
      }
    });
  } catch (error) {
    console.error('获取商品详情失败:', error);
    res.status(500).json({ error: error.message });
  }
});

// 查看所有分类
router.get('/categories', async (req, res) => {
  try {
    const [categories] = await db.query('SELECT * FROM categories');
    res.json({
      data: categories
    });
  } catch (error) {
    console.error('获取分类失败:', error);
    res.status(500).json({ error: error.message });
  }
});

module.exports = router;